package com.lv.shiro;



import com.lv.api.SellerServiceApi;
import com.lv.api.UserServiceApi;
import com.lv.data.Result;
import com.lv.dto.SellerDto;
import com.lv.dto.UserDto;
import com.lv.enums.ToKenEnum;
import com.lv.exception.LoginException;
import com.lv.model.Admin;
import com.lv.service.AdminService;
import org.apache.ibatis.jdbc.Null;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;

public class LoginRealm extends AuthorizingRealm {

    @Autowired
    private AdminService as;

    @Autowired
    private SellerServiceApi ssa;
    @Autowired
    private UserServiceApi usa;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //给资源进行授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //添加资源的授权字符串
        info.addStringPermission("del");
        return info;
    }

    //认证(登录)
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //取出UserNamePasswordTOKEN
        LoginToKen token = (LoginToKen) authenticationToken;
        //获取账号
        String username = token.getUsername();
        //tokenEnum
        ToKenEnum tokenEnum = token.getTokenEnum();
        if (tokenEnum.equals(ToKenEnum.ADMIN)){
            //去查询
            Admin admin = as.getAdminByUserName(username);
            //进行判断
            if (admin == null) {
                return null;
            }
            return new SimpleAuthenticationInfo(admin,admin.getPassword(),ByteSource.Util.bytes(admin.getSalt()),"LoginRealm");
        } else if (tokenEnum.equals(ToKenEnum.SELLER)){

            Result<SellerDto> result = ssa.getSellerByName(username);

            SellerDto sellerDto = result.getData();
            if (sellerDto == null) {
                return null;
            }

            return new SimpleAuthenticationInfo(sellerDto,sellerDto.getPassword(),ByteSource.Util.bytes(sellerDto.getSalt()),"LoginRealm");

        }else if (tokenEnum.equals(ToKenEnum.USER)){

            Result<UserDto> result = usa.getSellerByName(username);

            UserDto userDto = result.getData();
            if (userDto == null) {
                return null;
            }
            if (!"Y".equals(userDto.getStatus())){
                throw new LoginException("状态异常");
            }
            return new SimpleAuthenticationInfo(userDto,userDto.getPassword(),ByteSource.Util.bytes(userDto.getSalt()),"LoginRealm");

        }

        return null;


    }
}
